import logging
from datetime import datetime
from functools import wraps
from .Database import get_session
from models.models import JobExecutionHistory
from .db_scheduler import db_scheduler

logger = logging.getLogger(__name__)
def monitor_task(func):
    """
    任务执行监控装饰器
    自动记录任务执行历史
    """
    @wraps(func)
    def wrapper(*args, **kwargs):
        # 从 kwargs 中获取 job_id，如果没有则使用函数名
        job_id = kwargs.get('job_id', func.__name__)

        db = None
        try:
            # 获取数据库会话
            db = next(get_session())

            start_time = datetime.now()

            # 执行原始函数
            result = func(*args, **kwargs)

            # 记录成功执行
            execution = JobExecutionHistory(
                job_id=job_id,
                status="success",
                execution_time=start_time,
                result=str(result)[:1000] if result else None
            )
            db.add(execution)
            db.commit()

            logger.info(f"任务 {job_id} 执行成功")
            return result

        except Exception as e:
            # 记录失败执行
            if db:
                try:
                    execution = JobExecutionHistory(
                        job_id=job_id,
                        status="failed",
                        execution_time=datetime.now(),
                        error_message=str(e)[:1000]
                    )
                    db.add(execution)
                    db.commit()
                    logger.info(f"任务 {job_id} 执行失败，已记录错误")
                except Exception as db_error:
                    logger.error(f"记录执行历史失败: {db_error}")

            logger.error(f"任务 {job_id} 执行失败: {e}")
            raise

        finally:
            if db:
                try:
                    db.close()
                except Exception as close_error:
                    logger.warning(f"关闭数据库连接失败: {close_error}")

    return wrapper  # 直接返回 wrapper 函数